/*
 * @ProjectName: 编程学习
 * @Copyright:   2020 HangZhou Yiyuery Dev, Ltd. All Right Reserved.
 * @address:     微信搜索公众号「架构探险之道」获取更多资源。
 * @date:        2020/9/12 8:44 下午
 * @blog:         https://yiyuery.blog.csdn.net/
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.jvm.reference;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Yiyuery
 * @date 2020/9/12 8:44 下午
 */
public class JvmReferenceTest3 {
    private static List<Object> list = new ArrayList<>();

    public static void main(String[] args) {
        //-Xms2M -Xmx3M
        testWeakReference(10);
    }

    private static void testWeakReference2(int m) {
        byte[] buff = null;
        for (int i = 0; i < m; i++) {
            buff = new byte[1024 * 1024 * 2];
            WeakReference<byte[]> sr = new WeakReference<>(buff);
            list.add(sr);
        }
        for (int i = 0; i < list.size(); i++) {
            Object obj = ((WeakReference) list.get(i)).get();
            System.out.println(obj);
        }

        System.out.println("buff: " + buff.toString());
    }

    //get available memory in MB
    public static long getFreeMemory() {
        return Runtime.getRuntime().freeMemory() / (1024 * 1024);
    }

    //get total memory in MB
    public static long getTotalMemory() {
        return Runtime.getRuntime().totalMemory() / (1024 * 1024);
    }

    private static void testWeakReference(int m) {
        List<WeakReference<Object>> list = new ArrayList<>();
        for (; m > 0; m--) {
            byte[]  buff = new byte[1024 * 1024 * 2];
            WeakReference<Object> sr = new WeakReference<>(buff);
            list.add(sr);
            System.out.println("Free memory after add list size:  " + list.size()
                    + " is " + getFreeMemory() + "MB");
        }
        System.out.println("Current memory use: " + (getTotalMemory() - getFreeMemory()) + "MB");
        System.out.println("Total memory is: " + getTotalMemory() + "MB");
        System.gc();
        //输出
        for (WeakReference<Object> item : list) {
            System.out.println(item.get());
        }
        System.out.println("--------------------------------");
    }

}
